package cn.jn.lhm.teacher.listen;

import cn.jn.lhm.service.config.exception.GlobalException;
import cn.jn.lhm.teacher.entity.EduSubject;
import cn.jn.lhm.teacher.entity.excel.SubjectData;
import cn.jn.lhm.teacher.service.EduService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @author LHM
 * @Tips 热爱每一天，奋斗每一天
 * @date 2020/6/1 - 21:39
 */
public class SubjectListener extends AnalysisEventListener<SubjectData> {

    //由于 SubjectListener 不能交给spring的管理，需要自己new ，不能注入其他对象

    public EduService eduService;

    public SubjectListener(){}

    /**
     * 注入service方便后面的数据库操作
     * @param eduService
     */
    public SubjectListener(EduService eduService){
        this.eduService = eduService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //判断是否有数据
        if (subjectData == null){
            throw new GlobalException(20001,"文件数据为空");
        }
        //一行一行的读取文件，第一个值是一级分类，第二个值是二级分类
        EduSubject oneSubject = judgeOneSubject(this.eduService, subjectData.getOneSubject());
        if (oneSubject == null){
            //没有该分类
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            //设置一级分类的名称
            oneSubject.setTitle(subjectData.getOneSubject());
            this.eduService.save(oneSubject);
        }
        //获取一级分类的Id值，因为使用的是主键字段生成，会自动赋值
        String pid = oneSubject.getId();
        EduSubject twoSubject = judgeTwoSubject(this.eduService, subjectData.getTwoSubject(), pid);
        //设置二级分类
        if (twoSubject == null){
            //没有该分类
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            //设置二级分类的名称
            twoSubject.setTitle(subjectData.getTwoSubject());
            this.eduService.save(twoSubject);
        }
    }

    /**
     * 判断一级分类是否存在
     * @param eduService service
     * @param name 分类名称
     * @return
     */
    private EduSubject judgeOneSubject(EduService eduService, String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        return eduService.querySubjectByPid(wrapper);
    }

    /**
     * 判断二级分类是否存在
     * @param eduService service
     * @param name 名称
     * @param pid 父级分类
     * @return
     */
    private EduSubject judgeTwoSubject(EduService eduService, String name, String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        return eduService.querySubjectByPid(wrapper);
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
